package com.bst.bsj.base.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.bst.bsj.portal.util.ControllerUtil;
import com.homewaimai.framework.web.request.session.LoginUser;

public class JsonBaseController {

    protected static final Logger logger           = Logger.getLogger(JsonBaseController.class);

    protected static final Logger requestLogger    = Logger.getLogger("httpRequestLogger");

    public static final String  ENCODING_CHARSET = "utf-8";

    protected String returnJsonResult(String code, Object data) {

        return ControllerUtil.returnJsonResult(code, data);
    }

    protected void writeJSON(HttpServletResponse response, String code, Object data) {

        String jsonResult = returnJsonResult(code, data);
        try {
            writeEntityToResponse(response, jsonResult);
        } catch (Exception e) {
            logger.error("writeJSON error:", e);
        }
    }

    protected void writeEntityToResponse(HttpServletResponse resp, String entity) throws IOException {
        resp.setContentType("text");
        resp.setCharacterEncoding(ENCODING_CHARSET);
        resp.getWriter().write(entity);
        resp.getWriter().flush();
    }

    protected void writeHttpResponse(HttpServletResponse resp, HttpResponse httpResponse) throws IOException {
        if (requestLogger.isInfoEnabled()) {
            requestLogger.info("Http response:" + httpResponse.toJson());
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        writeEntityToResponse(resp, httpResponse.toJson());
    }

    protected void writeJsonpHttpResponse(HttpServletResponse resp, HttpResponse httpResponse, String callback)
                                                                                                               throws IOException {
        if (requestLogger.isInfoEnabled()) {
            requestLogger.info("Http response:" + httpResponse.toJson());
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        writeJsonEntityToResponse(resp, callback + "(" + httpResponse.toJson() + ");");
    }

    private void writeJsonEntityToResponse(HttpServletResponse resp, String entity) throws IOException {
        resp.setContentType("application/json");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setCharacterEncoding(ENCODING_CHARSET);
        resp.getWriter().write(entity);
        resp.getWriter().flush();
    }

    protected String readEntityFromRequest(HttpServletRequest req) throws IOException {
        return IOUtils.toString(req.getInputStream(), ENCODING_CHARSET);
    }

    @SuppressWarnings("unchecked")
    protected <T> T readObjectFromReqEntity(HttpServletRequest req, Class<T> clazz) throws Exception {
        String reqEntity = readEntityFromRequest(req);
        req.getPathInfo();
        if (StringUtils.isBlank(reqEntity)) {
            logger.error("Request entity is blank. RemoteAddr:" + req.getRemoteAddr());
        } else {
            if (requestLogger.isInfoEnabled()) {
                requestLogger.info(String.format("Accept a request.url:%s entity:%s", req.getRequestURL(), reqEntity));
            }
        }

        InputVOCheck inputVO;
        try {
            inputVO = (InputVOCheck) JSON.parseObject(reqEntity, clazz);
        } catch (Exception e) {
            requestLogger.error("readObjectFromReqEntity fail:" + reqEntity, e);
            throw new Exception("-1");
        }

        int ret = inputVO.checkPara();
        if (0 != ret) {
            throw new Exception(String.valueOf(ret));
        }
        return (T) inputVO;

    }

    protected LoginUser getLoginUser(HttpServletRequest request) {

        return ControllerUtil.getLoginUser(request);

    }

}
